package com.xiaowu.commons.scan.shiro;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.sf.ehcache.Ehcache;

import org.apache.commons.collections.map.HashedMap;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.cache.ehcache.EhCacheManager;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import com.alibaba.fastjson.JSON;
import com.xiaowu.commons.utils.StaticParameter;
import com.xiaowu.web.model.Resource;
import com.xiaowu.web.model.User;
import com.xiaowu.web.service.IResourceService;
import com.xiaowu.web.service.IUserService;
import com.xiaowu.web.vo.ActiveUser;

/**
 * 自定义 realm
 * @author WH
 *
 */
public class UserRealm extends AuthorizingRealm{

	@Autowired
	private IUserService userService;
	
	@Autowired
	private IResourceService resourceService;
	
	@Autowired
	private EhCacheManager cacheManager;
	
	/**
	 * 授权
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		
		//从 principals获取主身份信息
		ActiveUser activeUser =   (ActiveUser) principals.getPrimaryPrincipal();
		Resource resource = new Resource();
		resource.setId(activeUser.getUserid());
		//得到用户的资源
		List<Resource> menuList = resourceService.selectMenuByUserId(resource);
		
		List<String> permissions = new ArrayList<String>();
		if(menuList!=null){
			for (Resource resource2 : menuList) {
				//将数据库的权限标签符放入集合
				permissions.add(resource2.getUrl());
			}
		}
		
		//查到权限数据，返回授权信息
		SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
		//将上边查询到授权信息填充到simpleAuthorizationInfo对象中
		simpleAuthorizationInfo.addStringPermissions(permissions);

		return simpleAuthorizationInfo;
	}

	/**
	 * 认证
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(
			AuthenticationToken token) throws AuthenticationException {
		
		// 第一步从token中取出身份信息
		String loginname = (String) token.getPrincipal();
		
		User u = new User();
		u.setLoginname(loginname);
		//查询用户正常状态（0正常，1禁用）
		u.setStatus(0);
		//根据登录账户查询用户信息
		User user = userService.findUserByLoginname(u);
		
		//如果查询不到返回null
		if(user==null){
			return null;
		}
		
		//得到密码
		String password = user.getPassword();
		//盐
		String salt = user.getSalt();
		
		//activeUser就是用户身份信息
		ActiveUser activeUser = new ActiveUser();
		
		activeUser.setUserid(user.getId());
		activeUser.setUserloginname(user.getLoginname());
		activeUser.setUsername(user.getName());
		
		Resource resource = new Resource();
		resource.setId(user.getId());
		//菜单
		//resource.setResourcetype(StaticParameter.ResourceStatusMenu);
		List<Resource> menuList = resourceService.selectMenuByUserId(resource);
		List<Resource> menusList = new ArrayList<Resource>();
		Map<String,String> urlMap = new HashMap<String,String>();
		for (Resource resource2 : menuList) {
			//菜单
			if(StaticParameter.ResourceStatusMenu==resource2.getResourcetype()){
				menusList.add(resource2);
			}
			urlMap.put(resource2.getUrl(), resource2.getDescription());
		}

		//资源放入缓存
		cacheManager.getCache("shiroCache").put("urlList", urlMap);
		
		//将用户菜单 设置到activeUser
		activeUser.setMenus(menusList);
		
		//将activeUser设置simpleAuthenticationInfo
		SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(
				activeUser, password, ByteSource.Util.bytes(salt) , this.getName());
		
		return simpleAuthenticationInfo;
	}

}
